import {
  ui
} from './ui'
import {
  localData
} from './localData'

const CART_NAME = 'cart'

export const cartTool = {
  add(goods, showToast = true) {
    const buyNum = goods.buyNum ?? 1
    let cart = this.getAll()
    const found = this.indexOf(goods._id)
    if (found >= 0) { // 购物车已存在
      cart[found].cartNum = (cart[found].cartNum ?? 1) + buyNum
    } else {
      goods.cartNum = buyNum
      cart.push(goods)
    }
    // console.log(found)
    localData.set(CART_NAME, cart)
    if (showToast) ui.toast(true, '加入购物车成功')
  },
  indexOf(id) {
    return this.getAll().findIndex(ele => ele._id == id)
  },
  get(id) {
    return this.getAll().find(ele => ele._id == id)
  },
  getAll() {
    return localData.get(CART_NAME) || []
  },
  update(goods) {
    const cart = this.getAll()
    const found = this.indexOf(goods._id)
    if (found >= 0) {
      cart[found] = goods
      localData.set(CART_NAME, cart)
    }
  },
  remove(id) {
    const found = this.indexOf(id)
    if (found >= 0) {
      let cart = this.getAll()
      cart.splice(found, 1)
      localData.set(CART_NAME, cart)
    }
  },
}